口径:GLM V1 · TP16 · prefill 一个 batch 3520 token · 每卡 SP 分片 220 行
一句话:SP MoE 让每张卡只当 1/16 的"token 包工头"——只管好自己那 220 行,算完直接交给下一层,全程谁都不需要看到全量。权重不切(每卡全量权重)。
def sp_shard(x: torch.Tensor) -> torch.Tensor:
"""Shard the token axis across TP ranks for sequence parallelism."""
return torch.ops.vllm.ascend_sp_shard_impl(x)
def _ascend_sp_shard_impl(x: torch.Tensor) -> torch.Tensor:
"""Pad the token axis (dim 0) to the TP multiple, then take this rank's chunk."""
tp_size = get_tensor_model_parallel_world_size()
tp_rank = get_tensor_model_parallel_rank()
sp_pad = (-x.shape[0]) % tp_size # 垫零到 16 的倍数
if sp_pad > 0:
x = F.pad(x, (0, 0) * (x.ndim - 1) + (0, sp_pad))
chunk = x.shape[0] // tp_size
out = x[tp_rank * chunk : (tp_rank + 1) * chunk] # ← 取本卡那段:220 行
return out.clone() if sp_pad == 0 else out
is_sequence_parallel=self.is_sequence_parallel, # L378 组装 FusedMoE 时声明 SP 模式
...
def forward(self, hidden_states, input_ids=None, hidden_states_fp32=None): # L383
num_tokens, hidden_dim = hidden_states.shape # 本卡只看到自己那份 token
...
router_logits = F.linear(router_input, self.gate.weight) # 路由:220 行各自选专家
fused_moe_out = self.experts(
hidden_states=hidden_states, # 分片直接进专家(dispatch 内部按 EP A2A)
router_logits=router_logits, input_ids=input_ids)
先答两句:SP 切行不是为了算 KV;token 间依赖只在 attention。
1. SP 切的是 MoE/FFN 这类“逐 token 前馈层”,不是为了算 KV。这类层的关键性质是:每个 token 的计算只依赖它自己那一行——token A 选什么专家、过什么 FFN,和 token B 毫无关系(就是一堆行独立的矩阵乘 + 门控)。所以按行切完全安全:切完各卡算各的,拼回来结果分毫不差。切行的目的是省 activation 通信与显存(每卡激活从 3520 行变 220 行,MoE 层间传递量降到 1/16),跟 KV 没关系。KV 的计算和写入发生在 attention 里(wkv 投影 + 写 KV cache,图 2 第②步),不在 MoE。
2. token 之间的依赖只存在于 attention 的交互步。真正的 token 间依赖是“每个 query 要看全序列的 K/V 算加权和”——这就是为什么 attention 不能像 MoE 那样简单按行切开各算各的,也解释了图 2 为什么约定“全量进、全量出”。
3. attention 内部要拆开看:哪步独立、哪步有依赖。
| attention 内部步骤 | token 依赖? | 能否直接吃 220 行分片 |
|---|---|---|
| Q/K/V 投影(wq_a / wq_b / wkv) | 无——纯逐行线性变换 | 能(这正是 #18671 分片直通的依据) |
| 写 KV cache | 无——每个 token 写自己的 KV | 能(每卡写自己 token 段,图 4 第②步) |
| 注意力交互(Q·K 加权和) | 有——每个 query 要读全序列 KV | 不能裸切,需要专门机制 |
| o_proj | 无——逐行 | 能 |
4. 真正的交互步,DSA-CP 怎么化解。解法是:KV 分段存储 + 全局编址跨段读——每卡存自己 token 段的 KV(省显存),indexer 选中的块通过全局 block table 跨段访问(token 依赖在这里被满足);算完再用 A2A + RS 归位(图 4 协同❶❷)。另外注意 softmax 是按 head 独立的(不同 head 互不相关),所以 head 维切(TP)也是安全的。
一句话:能按行切的地方(MoE/FFN/投影/写 KV——逐 token 独立)就切,省通信;不能切的地方(注意力交互——全序列依赖)用“KV 分段存 + 全局读 + 算完归位”来化解。SP 管“独立的部分”,DSA-CP 管“有依赖的部分”——两个特性各管一段,这才是它们能同开、也才会同开时打架的根本原因。
一句话:DSA-CP 让每张卡当 1/16 的"head 包工头"——但 head 的计算必须对着全部 token 做,所以它的门禁是"全量进、全量出"。
hidden_states = hidden_states_local
if need_gather_q_kv:
hidden_states = tensor_model_parallel_all_gather(hidden_states_local, dim=0) # ← 图 6 上栏❶ 冗余的源头
...
qr_local = self.q_norm(self.wq_a(hidden_states_local)) # ① Q 投影:直接用本卡行
q = self.wq_b(qr_local)
q = q.unflatten(-1, (self.num_heads, self.head_dim))
q = DeviceOperator.apply_dsa_q_rms(q, self.eps, self.q_norm_without_weight) # + RoPE
kv = self.wkv(hidden_states_cache)
kv = self.kv_norm(kv)
kv = kv.view(-1, 1, self.nope_head_dim + self.rope_head_dim)
torch.ops._C_ascend.inplace_partial_rotary_mul(kv.unsqueeze(1), cos, sin, ...)
get_dsa_attn_kv_plan(self.vllm_config).dsa_kv_compress_scatter(
swa_kv_cache, kv, swa_metadata.req_metadata.slot_mapping) # ← KV 写进本卡负责的段
compress_topk_idxs = self._indexer_select_topk(
x=hidden_states_local, qr=qr_local,
kv_cache=kv_cache, metadata=layer_metadata,
cos=local_cos, sin=local_sin, ...)
一句话:TP 把权重矩阵本身切成 16 份、分发到 16 张卡,而 token 一行不少,每卡都要全算——所以图 2 的 attention(TP 按 head 切)必须收 3520 行全量、出部分和再归约。
self.wq_a = ReplicatedLinear(...) # L498 复制·每卡整份(Q 降维投影) wq_b_cls = ReplicatedLinear if self.enable_dsa_cp else ColumnParallelLinear self.wq_b = wq_b_cls(...) # L508-509 DSA-CP 开时整份复制,关时按 head 列切 self.wkv = ReplicatedLinear(...) # L518 复制(MLA 的 KV 单份 latent,无 head 维) self.wo_a = ColumnParallelLinear(...) # L527 列切(竖条) self.wo_b = RowParallelLinear(...) # L539 行切(横条)→ 部分和需归约
# ... replicated and no collective ops are needed.
# Otherwise we use standard TP with an allreduce at the end.
self.gate_up_proj = MergedColumnParallelLinear( # L236 竖条:列切
hidden_size, [intermediate_size] * 2,
disable_tp=is_sequence_parallel, ...) # SP 时整份(不切)
self.down_proj = RowParallelLinear( # L244 横条:行切
intermediate_size, hidden_size,
reduce_results=reduce_results, ...)
怎么协同:①② 两步 16 卡各干各的(每卡 220 行 × 自己 4 头,KV 各写自己的段);然后只发生两次跨卡协同——A2A 把"每卡一小段 × 全部 head"换成"全量 3520 行 × 自己的 head",让 o_proj 能按图 3 的权重切片行并行;各卡算出部分和后 RS 一次求和取回,恢复每卡 220 行。整层就这两笔通信,门口不拼全量。
# Convert [local tokens, all heads] to [all tokens, local heads]. ← 协同❶
# The row-parallel projection is unreduced; scale its partial sums
# before the single RS restores the caller's local token shard.
send = (attn_output.view(-1, self.tp_size, self.num_heads * self.v_head_dim)
.permute(1, 0, 2).reshape(-1, self.num_heads * self.v_head_dim))
sharded_output = torch.empty_like(send)
torch.distributed.all_to_all_single(sharded_output, send, group=tp_group.device_group)
projected_output = self.o_proj(sharded_output)[0] # 行并行投影 → 未归约部分和
if output_scale != 1.0:
projected_output.mul_(output_scale) # FP16 溢出保护(先缩放再归约)
torch.distributed.reduce_scatter_tensor( ← 协同❷ 单次 RS
output, projected_output.contiguous(), group=tp_group.device_group)
def restore_tp_heads(output, tp_group):
"""Exchange [local tokens, all heads] for [all tokens, local heads]."""
if tp_group.world_size == 1:
return output
tokens, heads, width = output.shape
local_heads = heads // tp_group.world_size
send = (output.view(tokens, tp_group.world_size, local_heads, width)
.permute(1, 0, 2, 3).contiguous().view(-1, local_heads, width))
recv = torch.empty_like(send)
dist.all_to_all_single(recv, send, group=tp_group.device_group)
return recv
对照图 4 读:中间的计算骨架一步不少——①QKV、②写 KV+稀疏注意力、协同 A2A、④o_proj 全都还在;差别只在门口和出口:SP 递来的 220 行分片先被 ❌❶ all-gather 拼回 3520 行全量(此后每卡都在全量上重复计算),出门时全量输出再被 ❌❸ 垫零 + reduce-scatter 切回 220 行。两笔橙色搬运每层都来一次(×78 层),就是长文 prefill TTFT 劣化的主因②;修复后(图 6 下栏)分片原样直通,只剩必要的 A2A 与单次 RS。两笔冗余的源码证据见图 6 的源码框。
冲突:图 1 的 MoE 递出 220 行分片,图 2/3 的 attention 只收 3520 行全量——模型层只能每层"AG 拼全量 → 算 → RS 切回"(上栏)。修复:#18671 新增 supports_sequence_parallel_input / forward_sequence_parallel / already_sequence_parallel 协商接口,让 220 行分片原样穿过 attention(下栏)——也就是回到图 4 的正常形态;必要的 A2A 与单次 RS 收编进后端;仅 V1 + PP=1 + SP MoE + DSA-CP 全满足时启用,其余自动回退老路径。
hidden_states = hidden_states_local
if need_gather_q_kv:
hidden_states = tensor_model_parallel_all_gather(hidden_states_local, dim=0)
# ↑ 220 行 → 3520 行:把 SP 分片拼回全量才能进 attention(每层都来一次)
def _ascend_sp_reduce_scatter_impl(x: torch.Tensor) -> torch.Tensor:
"""Pad rows to the TP multiple, then reduce-scatter across TP ranks."""
tp_size = get_tensor_model_parallel_world_size()
sp_pad = (-x.shape[0]) % tp_size
if sp_pad > 0: # 3520 不整除时垫零
pad_shape = [sp_pad, x.shape[1]]
x = torch.cat([x, x.new_zeros(pad_shape)], dim=0)
output = _custom_collective("custom_reduce_scatter", x)
if output is not None:
return output
return tensor_model_parallel_reduce_scatter(x, 0) # 全量 → 本卡 220 行
class AscendGlmMoeDsaForCausalLM(GlmMoeDsaForCausalLM):
def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
if (
not vllm_config.use_v2_model_runner # V1
and vllm_config.parallel_config.pipeline_parallel_size == 1 # PP=1
and vllm_config.parallel_config.use_sequence_parallel_moe # SP MoE
and enable_dsa_cp() # DSA-CP
):
self.model_cls = AscendDSACPModel # ← 四条件全满足才走新路径
...
input_is_sequence_parallel = ( # L1001 形状判定:hidden 行数 != positions 行数
self.use_sequence_parallel_moe and residual is not None
and hidden_states.shape[0] != positions.shape[0])
...
hidden_states = self.mlp(hidden_states, already_sequence_parallel=True) # L1025
# ↑ 告诉 MoE:"进来的已是分片,出去的也保持分片"
already_sequence_parallel=True 就是 MoE 与 attention 的"分片口径"握手。